<template>
  <div class="site-area-container">
    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" type="card" class="site-tabs">
      <el-tab-pane label="站点管理" name="management">
        <el-row :gutter="20">
          <!-- 站点列表 -->
          <el-col :span="9" class="site-list-col">
            <el-card shadow="never" class="site-list-card">
              <div class="flex justify-between items-center mb-2">
                <span class="font-bold">站点列表</span>
                <el-button type="primary" icon="Plus" size="small" @click="openSiteDialog()">新增站点</el-button>
              </div>
              <el-table
                ref="siteTableRef"
                :data="siteList"
                highlight-current-row
                @current-change="handleSiteSelect"
                :row-class-name="row => row.id === currentSiteId ? 'is-selected' : ''"
                style="height: 60vh;overflow:auto"
              >
                <el-table-column prop="name" label="站点名称" min-width="120" />
                <el-table-column prop="address" label="地址" min-width="120" show-overflow-tooltip />
                <el-table-column label="地图标记" width="100" align="center">
                  <template #default="scope">
                    <el-tag v-if="scope.row.latitude && scope.row.longitude" type="success" size="small">
                      已标记
                    </el-tag>
                    <el-tag v-else type="info" size="small">
                      未标记
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template #default="scope">
                    <div class="action-buttons">
                      <el-button 
                        link 
                        size="small" 
                        icon="Edit" 
                        @click.stop="openSiteDialog(scope.row)"
                        class="action-btn edit-btn"
                      >
                        编辑
                      </el-button>
                      <el-button 
                        link 
                        size="small" 
                        icon="Delete" 
                        type="danger" 
                        @click.stop="deleteSite(scope.row)"
                        class="action-btn delete-btn"
                      >
                        删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>

          <!-- 区域树管理 -->
          <el-col :span="15">
            <el-card shadow="never" class="area-tree-card">
              <div class="area-tree-header">
                <div class="area-tree-title">
                  <el-icon class="area-tree-icon"><FolderOpened /></el-icon>
                  <span class="area-tree-text">区域树</span>
                  <el-tag v-if="currentSite?.name" type="info" size="small" class="site-tag">
                    {{ currentSite.name }}
                  </el-tag>
                </div>
                <el-button 
                  type="primary" 
                  icon="Plus" 
                  size="small" 
                  :disabled="!currentSiteId" 
                  @click="openAreaDialog()"
                  class="add-area-btn"
                >
                  新增区域
                </el-button>
              </div>
              
              <div v-if="!currentSiteId" class="area-tree-empty">
                <el-empty description="请先选择左侧站点" :image-size="120">
                  <template #image>
                    <el-icon class="empty-icon"><Folder /></el-icon>
                  </template>
                </el-empty>
              </div>
              
              <div v-else class="area-tree-content">
                <div class="area-tree-stats">
                  <el-tag type="success" size="small">
                    共 {{ getTotalAreaCount(areaTree) }} 个区域
                  </el-tag>
                </div>
                
                <el-tree
                  :data="areaTree"
                  :props="treeProps"
                  node-key="id"
                  draggable
                  @node-drop="handleAreaDrop"
                  default-expand-all
                  highlight-current
                  @node-click="handleAreaSelect"
                  class="custom-tree"
                >
                  <template #default="{ data }">
                    <div class="tree-node-content">
                      <div class="tree-node-info">
                        <el-icon class="tree-node-icon">
                          <Folder v-if="data.children && data.children.length > 0" />
                          <Document v-else />
                        </el-icon>
                        <span class="tree-node-label">{{ data.name }}</span>
                        <el-tag v-if="data.children && data.children.length > 0" type="info" size="small" class="child-count">
                          {{ data.children.length }}
                        </el-tag>
                      </div>
                      <div class="tree-node-actions">
                        <el-button 
                          link 
                          size="small" 
                          icon="Edit" 
                          @click.stop="openAreaDialog(data)"
                          class="tree-action-btn tree-edit-btn"
                        >
                          编辑
                        </el-button>
                        <el-button 
                          link 
                          size="small" 
                          icon="Delete" 
                          type="danger" 
                          @click.stop="deleteArea(data)"
                          class="tree-action-btn tree-delete-btn"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                  </template>
                </el-tree>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 地图视图标签页 -->
      <el-tab-pane label="地图视图" name="map">
        <SiteMap />
      </el-tab-pane>
    </el-tabs>

    <!-- 站点表单对话框 -->
    <el-dialog v-model="siteDialogVisible" :title="siteForm.id ? '编辑站点' : '新增站点'" width="600px">
      <el-form :model="siteForm" :rules="getSiteRules()" ref="siteFormRef" label-width="100px">
        <el-form-item label="所属客户" prop="customerId" v-if="!siteForm.id">
          <el-select v-model="siteForm.customerId" placeholder="请选择所属客户" style="width: 100%">
            <el-option
              v-for="customer in customerList"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属客户" v-if="siteForm.id">
          <el-input v-model="siteForm.customerName" disabled placeholder="所属客户" />
        </el-form-item>
        <el-form-item label="站点名称" prop="name">
          <el-input v-model="siteForm.name" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="siteForm.address" placeholder="请输入站点地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="siteForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
        
        <!-- 地图相关字段 -->
        <el-divider content-position="left">地图设置</el-divider>
        <el-form-item label="纬度">
          <el-input v-model="siteForm.latitude" placeholder="请输入纬度" type="number" step="0.000001" />
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="siteForm.longitude" placeholder="请输入经度" type="number" step="0.000001" />
        </el-form-item>
        <el-form-item label="标记颜色">
          <el-color-picker v-model="siteForm.markerColor" />
        </el-form-item>
        <el-form-item label="标记描述">
          <el-input v-model="siteForm.markerDescription" type="textarea" :rows="2" placeholder="请输入标记描述" />
        </el-form-item>
        <el-form-item label="显示在地图">
          <el-switch v-model="siteForm.showOnMap" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="siteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSiteForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 区域表单对话框 -->
    <el-dialog v-model="areaDialogVisible" :title="areaForm.id ? '编辑区域' : '新增区域'" width="500px">
      <el-form :model="areaForm" :rules="areaRules" ref="areaFormRef" label-width="100px">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="areaForm.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="父级区域" prop="parentAreaId">
          <el-tree-select
            v-model="areaForm.parentAreaId"
            :data="areaTree"
            :props="treeProps"
            :disabled="!currentSiteId"
            placeholder="请选择父级区域（可选）"
            clearable
            check-strictly
            :default-expand-all="true"
            :render-after-expand="false"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="areaDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAreaForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FolderOpened, Folder, Document } from '@element-plus/icons-vue'
import SiteAPI from '@/api/system/site.api.js'
import AreaAPI from '@/api/system/area.api.js'
import CustomerAPI from '@/api/system/customer.api.js'
import SiteMap from './map.vue'

const siteList = ref([])
const areaTree = ref([])
const customerList = ref([])
const currentSiteId = ref(null)
const currentSite = computed(() => siteList.value.find(s => s.id === currentSiteId.value) || null)
const activeTab = ref('management')

const siteDialogVisible = ref(false)
const areaDialogVisible = ref(false)
const siteForm = reactive({ id: null, customerId: null, name: '', address: '', remark: '', latitude: null, longitude: null, markerColor: '#FF0000', markerDescription: '', showOnMap: true })
const areaForm = reactive({ id: null, name: '', parentAreaId: 0 })
const siteFormRef = ref()
const areaFormRef = ref()
const siteTableRef = ref()

const siteRules = {
  customerId: [{ required: true, message: '请选择所属客户', trigger: 'change' }],
  name: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入站点地址', trigger: 'blur' }]
}

// 动态验证规则，编辑时不验证客户ID
const getSiteRules = () => {
  const rules = {
    name: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
    address: [{ required: true, message: '请输入站点地址', trigger: 'blur' }]
  }
  
  // 只有新增时才验证客户ID
  if (!siteForm.id) {
    rules.customerId = [{ required: true, message: '请选择所属客户', trigger: 'change' }]
  }
  
  return rules
}
const areaRules = {
  name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
  siteId: [{ required: true, message: '请先选择站点', trigger: 'change' }]
}

const treeProps = { label: 'name', children: 'children', value: 'id' }

const hierarchyOptions = ref([]);
const hierarchyProps = {
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true,
  multiple: false,
};

// 获取客户列表
const fetchCustomers = async () => {
  try {
    const res = await CustomerAPI.getPage({ currentPage: 1, pageSize: 1000 })
    customerList.value = res.records || []
  } catch (error) {
    console.error('获取客户列表失败:', error)
  }
}

// 获取完整的层级数据
const fetchHierarchyOptions = async () => {
  try {
    const res = await SiteAPI.getFullHierarchy();
    
    // request工具已经处理了响应，直接返回data部分
    if (res && Array.isArray(res)) {
      hierarchyOptions.value = res || [];
    } else {
      console.warn('层级数据为空或格式不正确:', res);
      hierarchyOptions.value = [];
    }
  } catch (error) {
    console.error('获取层级数据失败:', error);
    console.error('错误详情:', error.response || error);
  }
}

// 获取站点列表
const fetchSites = async () => {
  try {
    // 直接从站点API获取站点列表，而不是从客户API获取
    const res = await SiteAPI.getPage({ currentPage: 1, pageSize: 1000 })
    siteList.value = res.records || res.list || []
    
    // 自动选中第一个站点
    if (siteList.value.length > 0 && !currentSiteId.value) {
      const firstSite = siteList.value[0]
      currentSiteId.value = firstSite.id
      // 设置表格当前行
      nextTick(() => {
        siteTableRef.value?.setCurrentRow(firstSite)
      })
      fetchAreaTree()
    }
  } catch (error) {
    console.error('获取站点列表失败:', error)
    // 如果站点API不存在，回退到从客户API获取
    try {
      const res = await CustomerAPI.getPage({ currentPage: 1, pageSize: 1000 })
      siteList.value = res.records.flatMap(c => c.sites || [])
      
      // 自动选中第一个站点
      if (siteList.value.length > 0 && !currentSiteId.value) {
        const firstSite = siteList.value[0]
        currentSiteId.value = firstSite.id
        // 设置表格当前行
        nextTick(() => {
          siteTableRef.value?.setCurrentRow(firstSite)
        })
        fetchAreaTree()
      }
    } catch (fallbackError) {
      console.error('回退获取站点列表也失败:', fallbackError)
    }
  }
}

// 获取区域树
const fetchAreaTree = async () => {
  if (!currentSiteId.value) {
    areaTree.value = []
    return
  }
  try {
    const res = await SiteAPI.getAreaTree(currentSiteId.value)
    // 如果后端返回失败状态但数据为空，也当作成功处理
    if (res && Array.isArray(res)) {
      areaTree.value = res
    } else {
      areaTree.value = []
    }
  } catch (error) {
    console.error('获取区域树失败:', error)
    areaTree.value = []
  }
}

const handleSiteSelect = (row) => {
  currentSiteId.value = row?.id
  fetchAreaTree()
}

const openSiteDialog = (row) => {
  if (row) {
    Object.assign(siteForm, row)
  } else {
    Object.assign(siteForm, { id: null, customerId: null, name: '', address: '', remark: '', latitude: null, longitude: null, markerColor: '#ff0000', markerDescription: '', showOnMap: true })
  }
  siteDialogVisible.value = true
}

const submitSiteForm = async () => {
  await siteFormRef.value.validate()
  try {
    if (siteForm.id) {
      await SiteAPI.update(siteForm)
    } else {
      await SiteAPI.create(siteForm)
    }
    ElMessage.success('操作成功')
    siteDialogVisible.value = false
    fetchSites()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

const deleteSite = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该站点吗？', '提示', { type: 'warning' })
    await SiteAPI.delete(row.id)
    ElMessage.success('删除成功')
    fetchSites()
    if (currentSiteId.value === row.id) {
      currentSiteId.value = null
      areaTree.value = []
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const openAreaDialog = (row) => {
  if (row) {
    // 编辑模式
    Object.assign(areaForm, {
      id: row.id,
      name: row.name,
      parentAreaId: row.parentAreaId || 0,
      siteId: currentSiteId.value
    })
  } else {
    // 新增模式
    Object.assign(areaForm, { 
      id: null, 
      name: '', 
      parentAreaId: 0,
      siteId: currentSiteId.value
    })
  }
  areaDialogVisible.value = true
}

const submitAreaForm = async () => {
  // 验证是否选择了站点
  if (!currentSiteId.value) {
    ElMessage.error('请先选择站点')
    return
  }
  
  await areaFormRef.value.validate()
  areaForm.siteId = currentSiteId.value
  
  // 确保parentAreaId是数字类型
  if (areaForm.parentAreaId && typeof areaForm.parentAreaId === 'string') {
    areaForm.parentAreaId = parseInt(areaForm.parentAreaId)
  }
  
  try {
    if (areaForm.id) {
      await AreaAPI.update(areaForm)
    } else {
      await AreaAPI.create(areaForm)
    }
    ElMessage.success('操作成功')
    areaDialogVisible.value = false
    fetchAreaTree()
  } catch (error) {
    console.error('提交失败:', error)
    console.error('错误详情:', error.response || error)
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
  }
}

const deleteArea = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该区域吗？', '提示', { type: 'warning' })
    await AreaAPI.delete(row.id)
    ElMessage.success('删除成功')
    fetchAreaTree()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleAreaDrop = async (draggingNode, dropNode, type) => {
  try {
    // 拖拽调整父级，需更新parentAreaId
    const newParentId = dropNode.data.id
    const updateData = { ...draggingNode.data, parentAreaId: newParentId, siteId: currentSiteId.value }
    await AreaAPI.update(updateData)
    ElMessage.success('区域层级调整成功')
    fetchAreaTree()
  } catch (error) {
    console.error('区域层级调整失败:', error)
    ElMessage.error('调整失败')
  }
}

const handleAreaSelect = (data) => {
  // 可扩展：点击区域节点后显示详情等
}

// 计算区域总数（递归计算）
const getTotalAreaCount = (areas) => {
  if (!areas || !Array.isArray(areas)) return 0
  let count = 0
  areas.forEach(area => {
    count++
    if (area.children && area.children.length > 0) {
      count += getTotalAreaCount(area.children)
    }
  })
  return count
}

onMounted(() => {
  fetchCustomers()
  fetchSites()
  fetchHierarchyOptions()
})
</script>

<style scoped>
.site-area-container {
  padding: 20px;
}

.site-list-col {
  min-width: 260px;
}

.site-list-card {
  height: 100%;
}

.area-tree-card {
  height: 100%;
}

/* 区域树样式 */
.area-tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.area-tree-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.area-tree-icon {
  font-size: 18px;
  color: #409eff;
}

.area-tree-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.site-tag {
  margin-left: 8px;
}

.add-area-btn {
  border-radius: 6px;
  font-weight: 500;
}

.area-tree-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.empty-icon {
  font-size: 48px;
  color: #c0c4cc;
}

.area-tree-content {
  min-height: 400px;
}

.area-tree-stats {
  margin-bottom: 16px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #67c23a;
}

/* 自定义树样式 */
.custom-tree {
  background: #fff;
  border-radius: 8px;
  padding: 8px;
}

.custom-tree :deep(.el-tree-node__content) {
  height: 48px;
  border-radius: 6px;
  margin: 2px 0;
  transition: all 0.3s ease;
}

.custom-tree :deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
  transform: translateX(4px);
}

.custom-tree :deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 500;
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 0;
}

.tree-node-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.tree-node-icon {
  font-size: 16px;
  color: #909399;
}

.tree-node-label {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.child-count {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 10px;
}

.tree-node-actions {
  display: flex;
  gap: 6px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.custom-tree :deep(.el-tree-node__content:hover) .tree-node-actions {
  opacity: 1;
}

.tree-action-btn {
  position: relative;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid transparent;
  min-width: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
}

.tree-action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.tree-edit-btn {
  color: #409eff;
  background: linear-gradient(135deg, #ecf5ff 0%, #f0f9ff 100%);
  border-color: #b3d8ff;
}

.tree-edit-btn:hover {
  color: #ffffff;
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
  border-color: #409eff;
}

.tree-delete-btn {
  color: #f56c6c;
  background: linear-gradient(135deg, #fef0f0 0%, #fff2f0 100%);
  border-color: #fbc4c4;
}

.tree-delete-btn:hover {
  color: #ffffff;
  background: linear-gradient(135deg, #f56c6c 0%, #ff4d4f 100%);
  border-color: #f56c6c;
}

/* 拖拽样式 */
.custom-tree :deep(.el-tree-node__content.is-drop-inner) {
  background-color: #409eff !important;
  color: white !important;
}

/* 站点列表操作按钮样式 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.action-btn {
  position: relative;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid transparent;
  min-width: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.edit-btn {
  color: #409eff;
  background: linear-gradient(135deg, #ecf5ff 0%, #f0f9ff 100%);
  border-color: #b3d8ff;
}

.edit-btn:hover {
  color: #ffffff;
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
  border-color: #409eff;
}

.delete-btn {
  color: #f56c6c;
  background: linear-gradient(135deg, #fef0f0 0%, #fff2f0 100%);
  border-color: #fbc4c4;
}

.delete-btn:hover {
  color: #ffffff;
  background: linear-gradient(135deg, #f56c6c 0%, #ff4d4f 100%);
  border-color: #f56c6c;
}

/* 表格行悬停效果 */
.site-list-card :deep(.el-table__row:hover) .action-buttons {
  opacity: 1;
}

.site-list-card :deep(.el-table__row) .action-buttons {
  opacity: 0.8;
  transition: opacity 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tree-node-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .tree-node-actions {
    opacity: 1;
    align-self: flex-end;
  }
  
  .action-buttons {
    flex-direction: row;
    gap: 8px;
  }
  
  .action-btn {
    min-width: 50px;
    padding: 4px 8px;
  }
}
</style>
